const URL = "https://api.letsdrink.com.cn/api/mem/";
const Nm = "https://api.letsdrink.com.cn/";
let token = '';
let session = '';
export function setAPIToken(str) {
  token = str.to;
  session = str.se
}

function disabled() {
  wx.showModal({
    title: '提示',
    content: '登录已过期',
    showCancel: false,
    confirmText: '重新登录',
    success: function (res) {
      wx.reLaunch({
        url: '/pages/QRcode/index',
      });

    }
  })
}

let patten = "",feature="";

//获取数据
export function homeData(url, params) {

  wx.showLoading({
    title: '加载中'
  });

  let result = new Promise(function (resolve, reject) {

    wx.request({
      url: URL + url,
      data: params.data || {},
      method: params.method || 'GET',
      header: {
        'Content-Type': 'application/json',
        'source': 'weapp',
        'Authorization': token
      },
      success: (res) => {
        if (res.statusCode == '401') {
          disabled();
          return
        };
        
        resolve(res);
        wx.hideLoading()
      },
      fail: (res) => {

        reject(res);
        wx.showModal({
          title: '',
          content: JSON.stringify(res),
        });
        params.fail && params.fail(res)
      }
    });

  })
  return result
};


export function userLogin(res) {
  console.log(res)
};

function location(origin) {

  wx.getLocation({
    success: function (res) {
      let data = res;
      data.origin = origin;
      homeData("location", { data: data, method: 'POST' })
    },
    fail: function (res) {
      console.log(["错误", res])
    }
  })


}


// 登录 1.1  （未与服务器产生登录状态，进行完整微信登录）
export function wxLogin(origin) {

  return new Promise(function (resolve, reject) {
    wx.login({
      success: function (res) {
        if (res.code) {
          let wxcode = res.code;

          //获取用户信息
          wx.getUserInfo({
            success: function (res) {
              wx.request({
                url: URL + 'wechat/login',
                data: {
                  code: wxcode,
                  userInfo: res.userInfo
                },
                method: 'POST',
                header: {
                  'Content-Type': 'application/json',
                  'source': 'weapp'
                },
                success: (res) => {
                  console.log(res)
                  let token = 'bearer ' + res.data.data.access_token;
                  let sess = res.data.data.session
                  // 将token储存在本地
                  wx.setStorage({
                    key: "token",
                    data: token
                  });
                  setAPIToken({ to: token, se: sess });
                  resolve(token);
                  if (origin) {
                    location(origin)
                  }
                },
                fail: (res) => {
                  console.log(res);
                  reject(res)
                }
              });

            },
            fail: function (res) {
              console.log("[wx.getUserInfo] fail:" + JSON.stringify(res))
            }
          })
        } else {
          console.log('获取用户登录态失败！' + res.errMsg);
        }
      },
      fail: function (res) {
        console.log('获取用户登录态失败！');
        reject(res)
      }
    })
  })
};

//用户信息
export function userData() {
  let data = new Promise(function (resolve, reject) {
    wx.getUserInfo({
      withCredentials: false,
      lang: '',
      success: function (res) {
        resolve(res)
      },
      fail: function (res) {
        console.log(res);
        reject(res)
      },
      complete: function (res) {

      },
    });
  })
  return data
};

//更新数据

export function getUpdate(nextPage, _this) {
  if (nextPage == null) {
    wx.showToast({
      title: '没有更多了',
      icon: "none",
      duration: 1000
    })
    return
  }
  let next = nextPage.split("/mem/");
  homeData(next[1].toString(), {}).then(res => {

    if (res.data.status == "success" && res.data.data.data.length != 0) {
      let data = res.data.data.data;
      // 为文章添加已选择（已收藏）的状态字段
      data.forEach(item => {
        item.selected = item.user_has_collect ? true : false;
        item.collect = item.user_want_drink ? true : false;
        item.drink = item.user_has_drink ? true : false;
      })
      _this.setData({
        homeData: _this.data.homeData.concat(data),
        nextPage: res.data.data.next_page_url == null ? null : res.data.data.next_page_url
      });
    } else if (res.data.status != "success") {
      wx.showToast({
        title: res.data.status + "错误",
        icon: "none"
      })
    }
  })
}


// 喝过的酒 想喝的酒 收藏文章
export const hasDrink = new RSAPI('has-drink');
export const wantDrink = new RSAPI('want-drink');
export const articleCollect = new RSAPI('article-collect');
// ResourceAPI 生成器
function RSAPI(pathname) {
  this.get = () => new Promise(function (resolve, reject) {
    wx.showLoading({
      title: 'loading',
    })

    wx.request({
      url: `${URL}${pathname}`,
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        'source': 'weapp',
        'Authorization': token
      },
      success: (res) => {
        wx.hideLoading()
        if (res.statusCode == '401') { disabled(); return }

        if (res.statusCode !== 200) {
          reject(res.data)
        } else {
          resolve(res.data)
        }
      },
      fail: (res) => {
        reject(res)
      }
    })
  }),

    this.post = (data) => new Promise(function (resolve, reject) {
      wx.showLoading({
        title: 'loading',
      })

      wx.request({
        url: `${URL}${pathname}`,
        method: 'POST',
        data: data,
        header: {
          'Content-Type': 'application/json',
          'source': 'weapp',
          'Authorization': token
        },
        success: (res) => {
          wx.hideLoading()
          if (res.statusCode == '401') { disabled(); return }

          if (res.statusCode !== 200) {
            reject(res.data)
          } else {
            resolve(res.data)
          }
        },
        fail: (res) => {
          reject(res)
        }
      })
    }),

    this.delete = (data) => new Promise(function (resolve, reject) {
      wx.showLoading({
        title: 'loading',
      })

      wx.request({
        url: `${URL}${pathname}-cancel`,
        method: 'POST',
        data: data,
        header: {
          'Content-Type': 'application/json',
          'source': 'weapp',
          'Authorization': token
        },
        success: (res) => {
          wx.hideLoading()
          if (res.statusCode == '401') { disabled(); return }
          if (res.statusCode !== 200) {
            reject(res.data)
          } else {
            resolve(res.data)
          }
        },
        fail: (res) => {
          reject(res)
        }
      })
    })
}

export const address = new ADSAPI('address')
// 地址api
function ADSAPI(pathname) {

  this.get = () => new Promise(function (resolve, reject) {
    wx.showLoading({
      title: 'loading',
    })

    wx.request({
      url: `${URL}${pathname}`,
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        'source': 'weapp',
        'Authorization': token
      },
      success: (res) => {
        wx.hideLoading()
        if (res.statusCode == '401') { disabled(); return }
        if (res.statusCode !== 200) {
          reject(res.data)
        } else {
          resolve(res.data)
        }
      },
      fail: (res) => {
        reject(res)
      }
    })
  }),

    this.post = (data) => new Promise(function (resolve, reject) {
      wx.showLoading({
        title: 'loading',
      })

      wx.request({
        url: `${URL}${pathname}`,
        method: 'POST',
        data: data,
        header: {
          'Content-Type': 'application/json',
          'source': 'weapp',
          'Authorization': token
        },
        success: (res) => {
          wx.hideLoading()
          if (res.statusCode == '401') { disabled(); return }
          if (res.statusCode !== 200) {
            reject(res.data)
          } else {
            resolve(res.data)
          }
        },
        fail: (res) => {
          reject(res)
        }
      })
    }),

    this.delete = (id) => new Promise(function (resolve, reject) {
      wx.showLoading({
        title: 'loading',
      })

      wx.request({
        url: `${URL}${pathname}/${id}`,
        method: 'DELETE',
        data: data,
        header: {
          'Content-Type': 'application/json',
          'source': 'weapp',
          'Authorization': token
        },
        success: (res) => {
          wx.hideLoading()
          if (res.statusCode == '401') { disabled(); return }
          if (res.statusCode !== 200) {
            reject(res.data)
          } else {
            resolve(res.data)
          }
        },
        fail: (res) => {
          reject(res)
        }
      })
    }),

    this.update = (data, ID) => new Promise(function (resolve, reject) {
      wx.showLoading({
        title: 'loading',
      })

      wx.request({
        url: `${URL}${pathname}/${ID}`,
        method: 'PUT',
        data: data,
        header: {
          'Content-Type': 'application/json',
          'source': 'weapp',
          'Authorization': token
        },
        success: (res) => {
          wx.hideLoading()
          if (res.statusCode == '401') { disabled(); return }
          if (res.statusCode !== 200) {
            reject(res.data)
          } else {
            resolve(res.data)
          }
        },
        fail: (res) => {
          reject(res)
        }
      })
    }),

    this.setDefault = (id) => new Promise(function (resolve, reject) {
      wx.showLoading({
        title: 'loading',
      })

      wx.request({
        url: `${URL}${pathname}-default/${id}`,
        method: 'POST',
        header: {
          'Content-Type': 'application/json',
          'source': 'weapp',
          'Authorization': token
        },
        success: (res) => {
          wx.hideLoading()
          if (res.statusCode == '401') { disabled(); return }
          if (res.statusCode !== 200) {
            reject(res.data)
          } else {
            resolve(res.data)
          }
        },
        fail: (res) => {
          reject(res)
        }
      })
    })
}



// 从服务器获取用户信息
export const getSeverUserInfo = function () {
  wx.showLoading({
    title: 'loading',
  })

  return new Promise(function (resolve, reject) {

    wx.request({
      url: `${URL}auth/me`,
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'source': 'weapp',
        'Authorization': token
      },
      success: (res) => {
        wx.hideLoading()
        if (res.statusCode == '401') { disabled(); return }
        if (res.statusCode !== 200) {
          reject(res.data)
        } else {
          resolve(res.data)
        }
      },
      fail: (res) => {
        reject(res)
      }
    })

  })
}

const article = '/pages/QRcode/index?navigator1=';//1
const product = '/pages/QRcode/index?navigator2=';//2

// 转发
export function Transpond(res) {
  console.log(res)
  if (res.from === 'button') {
    let Path = '/pages/QRcode/index',
      Title = 'Let `s Drink';
    let CON = res.target.dataset.type;
    if (CON) {
      CON = CON.split(',')
      console.log(CON)
      let n = CON[0], ID = CON[1], img = CON[2], title = CON[3];

      switch (n) {
        case '1': Path = article + ID; break;
        case '2': Path = product + ID; break;
      };

      return {
        title: title,
        path: Path,
        imageUrl: img
      }
    } else {
      return {
        title: Title,
        path: Path
      }
    }
  } else {
    return {
      title: 'Let `s Drink',
      path: '/pages/QRcode/index'
    }
  }
}

export function getPhoneNumber(option) {
  option = Object.assign(option, { session: session });
  console.log(option)
  return new Promise(function (resolve, reject) {

    wx.request({
      url: Nm + 'wechat/mobile',
      data: option,
      header: {
        'Content-Type': 'application/json',
        'source': 'weapp',
        'Authorization': token
      },
      method: 'post',
      success: function (res) {
        resolve(res)
      },
      fail:function(res){
      reject(res)
      }
    })
  })
}


module.exports = {
  homeData,
  wxLogin,
  userData,
  getUpdate,
  articleCollect,
  wantDrink,
  hasDrink,
  setAPIToken,
  getSeverUserInfo,
  address,
  Transpond,
  getPhoneNumber
}